package hidalgo.expenses.activity;

import hidalgo.expenses.R;
import hidalgo.expenses.SessionManager;
import hidalgo.expenses.adapter.AccountStringAdapter;
import hidalgo.expenses.constants.PaymentType;
import hidalgo.expenses.dao.AccountDao;
import hidalgo.expenses.dao.TransactionDao;
import hidalgo.expenses.entities.Account;
import hidalgo.expenses.entities.Transaction;
import hidalgo.expenses.utils.HideAnimation;
import hidalgo.expenses.utils.Properties;
import hidalgo.expenses.utils.Util;
import hidalgo.expenses.widgets.ActionBar;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class AddExpenseActivity extends BaseActivity {

	public static final String CALCULATOR_PACKAGE = "com.android.calculator2";
	public static final String CALCULATOR_CLASS = "com.android.calculator2.Calculator";
	public static final int DATE_DIALOG_ID = 0;
	public static final int PICTURE_RESULT = 100;
	private static final String TAG = "CAMERA ACTIVITY RESULT";

	private ActionBar actionBar;

	private Button btnCalculator;
	private Button btnCamera;
	private EditText etxtAmount;
	private Spinner spnPaymentType;
	private Spinner spnAccount;
	private EditText etxtDate;
	private EditText etxtdescription;

	private int year;
	private int month;
	private int day;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.add_transaction_activity);
		setUpActionBar();

		btnCalculator = (Button) findViewById(R.id.btnCalculator);
		btnCamera = (Button) findViewById(R.id.btnCamera);
		spnPaymentType = (Spinner) findViewById(R.id.spnPaymentType);
		spnAccount = (Spinner) findViewById(R.id.spnAccounts);
		etxtDate = (EditText) findViewById(R.id.etxtDate);
		etxtAmount = (EditText) findViewById(R.id.etxtAmount);
		etxtdescription = (EditText) findViewById(R.id.etxtDescription);

		populateAccounts();
		populatePaymentTypes();
		setDate();

		etxtDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});

		btnCalculator.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				/*
				 * Intent intent = new Intent();
				 * 
				 * intent.setAction(Intent.ACTION_MAIN);
				 * intent.addCategory(Intent.CATEGORY_LAUNCHER);
				 * intent.setComponent(new ComponentName(CALCULATOR_PACKAGE,
				 * CALCULATOR_CLASS));
				 * 
				 * AddExpenseActivity.this.startActivity(intent);
				 */

				Intent intent = new Intent(AddExpenseActivity.this,
						Calculator.class);
				startActivity(intent);

			}
		});

		btnCamera.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				AddExpenseActivity.this.startActivityForResult(camera,
						PICTURE_RESULT);

			}
		});

	}

	private void setDate() {
		final Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);

		etxtDate.setText(Util.getDateString(day, month, year));

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			// set date picker as current date
			final Calendar c = Calendar.getInstance();
			year = c.get(Calendar.YEAR);
			month = c.get(Calendar.MONTH);
			day = c.get(Calendar.DAY_OF_MONTH);

			return new DatePickerDialog(this, new OnDateSetListener() {

				public void onDateSet(DatePicker view, int selectedYear,
						int selectedMonth, int selectedDayOfMonth) {
					year = selectedYear;
					month = selectedMonth;
					day = selectedDayOfMonth;

					etxtDate.setText(Util.getDateString(day, month, year));

				}
			}, year, month, day);
		}
		return null;
	}



	private void populateAccounts() {

		new AsyncTask<Integer, Integer, ArrayList<Account>>() {

			protected void onPreExecute() {
				actionBar.showProgressBar();
				actionBar.getProgressBar().startLoading(
						Properties.progressBarSpeed);
			};

			@Override
			protected ArrayList<Account> doInBackground(Integer... params) {

				return AccountDao.getAccountsByUser(SessionManager.userId);
			}

			protected void onPostExecute(
					java.util.ArrayList<Account> accountList) {

				if (accountList != null) {
					AccountStringAdapter spinnerArrayAdapter = new AccountStringAdapter(
							AddExpenseActivity.this,
							android.R.layout.simple_spinner_item, accountList);

					spinnerArrayAdapter
							.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

					spnAccount.setAdapter(spinnerArrayAdapter);

				}

				actionBar.getProgressBar().completeLoading();
				actionBar.getProgressBar().startAnimation(
						new HideAnimation(1.0f, 1.0f, 1.0f, 0.0f, 500,
								actionBar.getProgressBar(), true));

			};

		}.execute();

	}

	private void populatePaymentTypes() {
		ArrayList<String> paymentTypes = new ArrayList<String>();

		paymentTypes.add(PaymentType.getPaymentName(PaymentType.efectivo));
		paymentTypes.add(PaymentType.getPaymentName(PaymentType.transferencia));
		paymentTypes.add(PaymentType.getPaymentName(PaymentType.deposito));
		paymentTypes.add(PaymentType.getPaymentName(PaymentType.cheque));
		paymentTypes.add(PaymentType.getPaymentName(PaymentType.otro));

		ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_item, paymentTypes);
		spinnerArrayAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnPaymentType.setAdapter(spinnerArrayAdapter);
	}

	private void setUpActionBar() {

		actionBar = (ActionBar) findViewById(R.id.actionBar);
		actionBar.setTitle("Nuevo Gasto");
		// set home icon that does nothing when the user clicks on it
		actionBar.setHomeLogo(R.drawable.ic_title_home_default,
				new OnClickListener() {
					public void onClick(View v) {
						AddExpenseActivity.this.finish();
					}
				});
		
		// sets an action icon that displays a Toast upon clicking
		actionBar.addActionIcon(R.drawable.ic_save, new OnClickListener() {
			public void onClick(View v) {

				Transaction transaction = new Transaction(Transaction.EXPENSE);

				transaction.setAmount(Float.parseFloat(etxtAmount.getText()
						.toString()));
				transaction.setDate(Util.getDateFromString(etxtDate.getText()
						.toString(), Util.SIMPLE_DATE_FORMAT));
				// transaction.setPaymentMethodId(spnPaymentType.get);
				transaction.setAccountId((int) spnAccount.getSelectedItemId());
				transaction.setPaymentMethodId(3);
				transaction
						.setDescription(etxtdescription.getText().toString());

				new AsyncTask<Transaction, Void, Boolean>() {

					@Override
					protected Boolean doInBackground(Transaction... params) {

						boolean success = false;
						Transaction transaction = params[0];

						success = TransactionDao.insert(transaction);

						return success;
					}

					protected void onPostExecute(Boolean success) {

						if (success) {
							Toast.makeText(AddExpenseActivity.this, "Guardado",
									Toast.LENGTH_SHORT).show();

							AddExpenseActivity.this.finish();
						} else {
							Toast.makeText(AddExpenseActivity.this,
									"Error al Guardar", Toast.LENGTH_SHORT)
									.show();
						}

					};

				}.execute(transaction);

			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == PICTURE_RESULT) //
			if (resultCode == Activity.RESULT_OK) {
				// Display image received on the view
				Bundle b = data.getExtras(); // Kept as a Bundle to check for
												// other things in my actual
												// code
				Bitmap pic = (Bitmap) b.get("data");

				if (pic != null) {
					// Display your image in an ImageView in your layout (if you
					// want to test it)

					Log.d(TAG, "Result success");
					/*
					 * pictureHolder = (ImageView)
					 * this.findViewById(R.id.IMAGE);
					 * pictureHolder.setImageBitmap(pic);
					 * pictureHolder.invalidate();
					 */
				}

			} else if (resultCode == Activity.RESULT_CANCELED) {
				Log.d(TAG, "Result Canceled");
			}
	}
}
